package src

import (
	"bytes"
	"embed"
	"fmt"
	"os/exec"
	"strconv"
	"strings"
)

//go:embed k8s-deployment.yaml
var k8sFile embed.FS

func ReplaceVariables(content string, config *Config) string {
	result := content
	result = strings.ReplaceAll(result, "${MODULE_NAME}", config.CalcK8sModuleName())
	result = strings.ReplaceAll(result, "${REPLICAS_NUM}", strconv.Itoa(config.GetReplicasNum()))
	result = strings.ReplaceAll(result, "${IMAGE_NAME}", GetImageName(config))
	result = strings.ReplaceAll(result, "${CPU_NUM}", strconv.Itoa(config.GetCpuNum()))
	result = strings.ReplaceAll(result, "${CONFIG_NAME}", config.GetConfigName())
	return result
}

func LoadAndReplaceConfig(config *Config) (string, error) {
	data, err := k8sFile.ReadFile("k8s-deployment.yaml")
	if err != nil {
		return "", fmt.Errorf("failed to read config file: %v", err)
	}
	configContent := string(data)
	replacedContent := ReplaceVariables(configContent, config)
	return replacedContent, nil
}

func ApplyConfigWithStdin(configContent, opt string, config *Config) error {
	fmt.Println("执行命令:", "kubectl", opt)
	cmd := exec.Command("kubectl", opt, "-f", "-")
	cmd.Stdin = bytes.NewBufferString(configContent)
	k8sConfigPath := "/opt/k8s/k8sConfig/config-" + config.Env
	cmd.Env = append(cmd.Env, fmt.Sprintf("KUBECONFIG=%s", k8sConfigPath))
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err := cmd.Run()
	if err != nil {
		fmt.Printf("Error executing kubectl %s: %v\n", opt, err)
		errorMsg := stderr.String()
		if NotFoundWhenDelete(config, opt, errorMsg) {
			return nil
		}
		fmt.Printf("Stderr: %s\n", errorMsg)
		return err
	}
	return nil
}

func NotFoundWhenDelete(config *Config, opt string, errorMsg string) bool {
	if strings.EqualFold(opt, "delete") {
		if strings.Contains(errorMsg, "NotFound") || strings.Contains(errorMsg, "not found") {
			fmt.Println("未发现应用,删除跳过")
			return true
		}
	}
	fmt.Println("删除Deployment成功,等待5s....")
	config.WaitForSeconds(5)
	return false
}
